package fr.jade.console.core;

import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import jline.Completor;

import org.objectweb.fractal.api.Component;

import fr.jade.util.FractalNavigator;

public class FractalCompletor implements Completor {

  private Environment env;
  String              delimiter = "/";

  public FractalCompletor(Environment env) {
    this.env = env;
  }

  public int complete(final String buffer, final int cursor, final List clist) {
    String start = (buffer == null) ? "" : buffer;

    Component current = (Component)env.getEnvVar("current");
//    if (buffer.endsWith("/")){
//      try {
//        current = FractalNavigator.find(current, buffer.substring(0, buffer.length()-1), true);
//      } catch (NoSuchInterfaceException e) {
//        e.printStackTrace();
//      }
//    }
    SortedSet candidates = new TreeSet();
    for(Component child : FractalNavigator.getChilds(current)){
    candidates.add(FractalNavigator.getName(child));
    }
    SortedSet matches = candidates.tailSet(start);

    for (Iterator i = matches.iterator(); i.hasNext();) {
      String can = (String) i.next();

      if (!(can.startsWith(start))) {
        break;
      }

      if (delimiter != null) {
        int index = can.indexOf(delimiter, cursor);

        if (index != -1) {
          can = can.substring(0, index + 1);
        }
      }

      clist.add(can);
    }

    if (clist.size() == 1) {
      clist.set(0, ((String) clist.get(0)) );
    }

    // the index of the completion is always from the beginning of
    // the buffer.
    return (clist.size() == 0) ? (-1) : 0;
  }


}
